﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace adb
{
    /// <summary>
    /// 连接数据
    /// </summary>
    public class dbBase
    {
        /// <summary>
        /// 
        /// </summary>
        public DbContextOptionsBuilder<MyDbContext> myOptionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
        /// <summary>
        /// 
        /// </summary>
        public DbContextOptionsBuilder<DeviceDbContext> deviceoOptionsBuilder = new DbContextOptionsBuilder<DeviceDbContext>();
        /// <summary>
        /// 构造函数
        /// </summary>
        public dbBase() {
            string myStr = "";
            string deviceStr = "";
            if (File.Exists(Environment.CurrentDirectory + "/appsettings.json")) {
                var configuration = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory)
                                             .AddJsonFile("appsettings.json")
                                             .Build();
                myStr = configuration["DBStr"];
                deviceStr = configuration["DBDeviceStr"];
            }
            else if (File.Exists(Environment.CurrentDirectory + "/App.config")) {
                myStr = System.Configuration.ConfigurationManager.AppSettings["DBStr"];
                deviceStr = System.Configuration.ConfigurationManager.AppSettings["DBDeviceStr"];
            }
            if(string.IsNullOrEmpty(myStr) || string.IsNullOrEmpty(deviceStr))
            {
                throw new Exception("数据库连接未设置,请使用App.config或appsettings.json来设置DBStr,DBDeviceStr,文件地址"+ Environment.CurrentDirectory + "\\appsettings.json");
            }
            myOptionsBuilder.UseSqlServer(myStr, options => options.CommandTimeout(90));
            deviceoOptionsBuilder.UseSqlServer(deviceStr, options => options.CommandTimeout(90));
        }
        /// <summary>
        /// 返回数据上下文,每次都是新的
        /// </summary>
        /// <returns></returns>
        public MyDbContext CreateMyDb() {
            return new MyDbContext(this.myOptionsBuilder.Options);
        }
        /// <summary>
        /// 返回数据上下文,每次都是新的
        /// </summary>
        /// <returns></returns>
        public DeviceDbContext CreateDeviceDb() {
            return new DeviceDbContext(this.deviceoOptionsBuilder.Options);
        }
    }
}
